package org.huiway.huipicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.huiway.huipicturebackend.api.aliyunai.AliYunAiApi;
import org.huiway.huipicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import org.huiway.huipicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import org.huiway.huipicturebackend.common.PageRequest;
import org.huiway.huipicturebackend.config.CosClientConfig;
import org.huiway.huipicturebackend.exception.BusinessException;
import org.huiway.huipicturebackend.exception.ErrorCode;
import org.huiway.huipicturebackend.exception.ThrowUtils;
import org.huiway.huipicturebackend.manager.CosManager;
import org.huiway.huipicturebackend.manager.upload.FilePictureUpload;
import org.huiway.huipicturebackend.manager.upload.PictureUploadTemplate;
import org.huiway.huipicturebackend.manager.upload.UrlPictureUpload;
import org.huiway.huipicturebackend.mapper.PictureMapper;
import org.huiway.huipicturebackend.mapper.UserPictureActionMapper;
import org.huiway.huipicturebackend.model.dto.file.UploadPictureResult;
import org.huiway.huipicturebackend.model.dto.picture.*;
import org.huiway.huipicturebackend.model.entity.Picture;
import org.huiway.huipicturebackend.model.entity.Space;
import org.huiway.huipicturebackend.model.entity.User;
import org.huiway.huipicturebackend.model.entity.UserPictureAction;
import org.huiway.huipicturebackend.model.enums.PictureLoveEnum;
import org.huiway.huipicturebackend.model.enums.PictureReviewStatusEnum;
import org.huiway.huipicturebackend.model.enums.UserRoleEnum;
import org.huiway.huipicturebackend.model.vo.picture.PictureVO;
import org.huiway.huipicturebackend.model.vo.user.UserVO;
import org.huiway.huipicturebackend.service.PictureService;
import org.huiway.huipicturebackend.service.SpaceService;
import org.huiway.huipicturebackend.service.UserPictureActionService;
import org.huiway.huipicturebackend.service.UserService;
import org.huiway.huipicturebackend.utils.ColorSimilarUtils;
import org.huiway.huipicturebackend.utils.ColorTrantsformUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hh
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-06-26 09:29:29
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private CosManager cosManager;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private COSClient cosClient;
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private UserPictureActionMapper userPictureActionMapper;
    @Resource
    private UserPictureActionService userPictureActionService;

    /**
     * 图片数据的校验
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 上传图片
     *
     * @param inputSource          文件输入源
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        if (loginUser == null || pictureUploadRequest == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        //11L为存储初始头像的空间
        if (spaceId != null && spaceId != 11L) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            //校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间上传图片条数已满");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 用于判断是新增还是更新图片
        Long pictureId = pictureUploadRequest.getId();
        // 如果是更新图片，需要校验图片是否存在
        Picture oldPicture;
        if (pictureId != null) {
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            //校验空间是否一致
            //没传SpaceId 则复用原有图片的SpaceId(这样也兼容了公共图库)
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                //传了SpaceId,必须和原图片地空间id一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间id不一致");
                }
            }
        } else {
            oldPicture = null;
        }
        // 上传图片，得到信息
        // 按照用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        Long loginUserId = loginUser.getId();
        if (spaceId == null) {
            //公共图库
            uploadPathPrefix = String.format("public/%s", loginUserId);
        } else {
            //如果是头像，则上传到头像目录下
            if (spaceId == 11L) {
                uploadPathPrefix = String.format("11/Avatar/%s", loginUserId);
            } else {
                //存储到个人空间
                uploadPathPrefix = String.format("space/%s", spaceId);
            }

        }
        //根据inputSource类型，选择上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId);   //指定空间ID
        picture.setUrl(uploadPictureResult.getUrl());   // 设置压缩后图片的url
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());  // 设置图片的缩略图url
        //支持外层传递图片名称
        String picName = uploadPictureResult.getPicName();
        if (StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicColor(ColorTrantsformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        picture.setUserId(loginUserId);
        //补充审核参数
        this.fillReviewParams(picture, loginUser);
        //操作数据库
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        //开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            //插入数据
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");
            if (finalSpaceId != null) {
                //更新空间的使用额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败，数据库操作失败");
            }
            return picture;
        });
        //自行实现，如果是更新，可以清理图片资源
        if (oldPicture != null) {
            this.clearPictureFile(oldPicture);
        }
        return PictureVO.objToVo(picture);
    }

    /**
     * 上传图片（可重新上传，可批量上传）
     *
     * @param multipartFiles
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public List<PictureVO> uploadPictureBatch(MultipartFile[] multipartFiles, PictureUploadRequest pictureUploadRequest, User loginUser) {
        if (loginUser == null || pictureUploadRequest == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        List<PictureVO> pictureVOList = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            PictureVO pictureVO = this.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
            pictureVOList.add(pictureVO);
        }
        return pictureVOList;
    }

    /**
     * 获取查询对象
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
//        String sortField = pictureQueryRequest.getSortField();
//        String sortOrder = pictureQueryRequest.getSortOrder();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        //< endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 始终按被喜欢数、被收藏数降序
        queryWrapper.orderByDesc("loveCount", "collectCount");
        return queryWrapper;
    }

    /**
     * 获取单个图片的封装类
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        // 查询是否点赞
        QueryWrapper<UserPictureAction> loveWrapper = new QueryWrapper<>();
        loveWrapper.eq("userId", loginUser.getId());
        loveWrapper.eq("pictureId", picture.getId());
        loveWrapper.eq("type", "Love");
        UserPictureAction loveAction = userPictureActionService.getOne(loveWrapper);
        pictureVO.setHasLoved(loveAction != null);

        // 查询是否收藏
        QueryWrapper<UserPictureAction> collectWrapper = new QueryWrapper<>();
        collectWrapper.eq("userId", loginUser.getId());
        collectWrapper.eq("pictureId", picture.getId());
        collectWrapper.eq("type", "Collect");
        UserPictureAction collectAction = userPictureActionService.getOne(collectWrapper);
        pictureVO.setHasCollected(collectAction != null);
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        // 尝试获取当前登录用户，未登录不会抛异常
        User loginUser = userService.tryGetLoginUser(request);

        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        //从图片列表中提取所有用户的ID集合，并批量查询这些用户的详细信息，然后按用户ID分组存储，以便后续快速查找
        Set<Long> userIdSet = pictureList.stream()
                .map(Picture::getUserId)
                .collect(Collectors.toSet());

        //userIdSet他就是经过去重的用户id 那么用户id肯定是全局唯一的 一一对应的
        // 那么就不存在一个userid对应多个用户情况（id->List<User>）
        List<User> userList = userService.listByIds(userIdSet);
        if (CollUtil.isEmpty(userList)) {
            return pictureVOPage;
        }
        // 构建用户ID到用户对象的映射表，用于后续快速查找
        Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(
                User::getId,
                user -> user
        ));

        // 获取图片ID列表，用于查询用户对图片的操作记录
        List<Long> pictureIds = pictureVOList.stream().map(PictureVO::getId).collect(Collectors.toList());

        // 查询当前登录用户对这些图片的操作记录（点赞/收藏等）
        List<UserPictureAction> actions = new ArrayList<>();
        if (loginUser != null && CollUtil.isNotEmpty(pictureIds)) {
            actions = userPictureActionService.list(
                    new QueryWrapper<UserPictureAction>()
                            .eq("userId", loginUser.getId())
                            .in("pictureId", pictureIds)
            );
        }
        // 构建图片ID到操作类型集合的映射
        Map<Long, Set<String>> picIdTypes = new HashMap<>();
        for (UserPictureAction action : actions) {
            picIdTypes.computeIfAbsent(action.getPictureId(), k -> new HashSet<>()).add(action.getType().toUpperCase());
        }
        // 合并两次遍历为一次：同时设置图片的点赞/收藏状态和关联的用户信息
        pictureVOList.forEach(vo -> {
            Set<String> types = picIdTypes.getOrDefault(vo.getId(), Collections.emptySet());
            vo.setHasLoved(types.contains("LOVE"));
            vo.setHasCollected(types.contains("COLLECT"));

            Long userId = vo.getUserId();
            User user = userMap.getOrDefault(userId, null);
            vo.setUser(userService.getUserVO(user));
        });

        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //1.校验参数
        if (pictureReviewRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.判断图片是否存在
        Picture oldPicture = this.getById(id);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //3.校验审核状态是否重复，已是该状态
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请勿重复审核");
        }
        //4.数据库操作
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    /**
     * 图片批量审核
     *
     * @param pictureReviewByBatchRequest
     * @param loginUser
     */
    @Override
    @Transactional
    public void doPictureReviewByBatch(PictureReviewByBatchRequest pictureReviewByBatchRequest, User loginUser) {
        //1.校验参数
        if (pictureReviewByBatchRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2.批量查询图片
        List<Long> idList = pictureReviewByBatchRequest.getIdList();
        // 获取要设置的状态值
        Integer reviewStatus = pictureReviewByBatchRequest.getReviewStatus();
        // 获取状态对应的枚举
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        log.info("批量审核图片，图片ID列表：{}，审核状态：{}", idList, reviewStatusEnum);
        // 操作的审核状态不能设置为待审核
        if (idList == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 查出符合条件的图片
        long count = lambdaQuery()
                .in(Picture::getId, idList)
                .eq(Picture::getReviewStatus, PictureReviewStatusEnum.REVIEWING.getValue())
                .count();
        if (count != idList.size()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "存在非待审核记录");
        }
        // 3.批量更新图片状态
        boolean result = lambdaUpdate().in(Picture::getId, idList)
                .set(Picture::getReviewStatus, reviewStatus)
                .set(Picture::getReviewerId, loginUser.getId())
                .set(Picture::getReviewTime, new Date())
                .update();
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    /**
     * 填充审核参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            //管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动过审");
        } else {
            //非管理员，无论是编辑还是创建默认都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量抓取和创建图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //1.校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        //名称前缀默认等于搜索关键字
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StringUtils.isBlank(searchText)) {
            namePrefix = searchText;
        }
        if (count > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多抓取30张图");
        }
        //2.抓取内容
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        //3.解析内容
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isEmpty(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        //遍历元素。依次处理伤处图片
        int uploadCount = 0;   //定义一个上传成功的数量
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过：{}", fileUrl);
                continue;
            }
            //处理图片的地址，防止转义或和对象存储冲突的问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            //4.上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id={}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 清理图片文件
     *
     * @param oldPicture
     */

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        boolean exists = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .exists();
        // 有不止一条记录用到了该图片，不清理
        if (exists) {
            return;
        }
        try {
            // 提取路径部分
            String picturePath = new URL(pictureUrl).getPath();
            cosManager.deleteObject(picturePath);
            // 清理缩略图
            String thumbnailUrl = oldPicture.getThumbnailUrl();
            if (StrUtil.isNotBlank(thumbnailUrl)) {
                String thumbnailPath = new URL(thumbnailUrl).getPath();
                cosManager.deleteObject(thumbnailPath);
            }
        } catch (MalformedURLException e) {
            log.error("处理图片删除时遇到格式错误的 URL。图片 URL: {}", pictureUrl, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "格式错误的 URL");
        }
        // FIXME 注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
//        cosManager.deleteObject(oldPicture.getUrl());
//        // 清理缩略图
//        String thumbnailUrl = oldPicture.getThumbnailUrl();
//        if (StrUtil.isNotBlank(thumbnailUrl)) {
//            cosManager.deleteObject(thumbnailUrl);
//        }
    }

    /**
     * 删除图片
     *
     * @param pictureId
     * @param loginUser
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        if (pictureId <= 0 || loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            if (oldPicture.getSpaceId() != null) {
                //更新空间的使用额度，释放额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败，数据库操作失败");
            }
            return null;
        });
        this.clearPictureFile(oldPicture);
    }

    /**
     * 批量删除图片
     *
     * @param pictureIds
     * @param spaceId
     * @param loginUser
     */
    @Override
    @Transactional
    public void deletePictureByBatch(List<Long> pictureIds, Long spaceId, User loginUser) {
        //1.获取和检验参数
        //List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        //Long spaceId = pictureEditByBatchRequest.getSpaceId();
        Space space = null;
        //公共图库管理员可以批量删除，公共图库的spaceId为null,space获取不到
        //私有空间或者团队空间，只有创建者可以删除
        if (spaceId != null) {
            space = spaceService.getById(spaceId);
        }
        //如果是公共图库，校验是否是管理员
        if (space == null && !loginUser.getUserRole().equals(UserRoleEnum.ADMIN.getValue())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //如果是私有空间或者团队空间，校验创建者
        if (space != null && !loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        if (CollUtil.isEmpty(pictureIds)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //3.遍历并删除图片
        for (Long count : pictureIds) {
            this.deletePicture(count, loginUser);
        }
    }

    /**
     * 编辑图片
     *
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    /**
     * 校验空间图片的权限
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        Long loginUserId = loginUser.getId();
        if (spaceId == null) {
            //公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUserId) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            //私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUserId)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

    }

    /**
     * 根据颜色搜索图片
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        //1.校验参数
        if (spaceId == null || picColor == null || loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.校验空间权限
        Space space = spaceService.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //3.查询该空间下的所有图片（必须要有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        //如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return new ArrayList<>();
        }
        //将颜色字符串转换为主色调
        Color targetColor = Color.decode(picColor);
        //4.计算相似度并排序
        List<Picture> sortedPictureList = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    String hexColor = picture.getPicColor();
                    //没有主色调的图片，默认排序到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    //计算相似度
                    //返回的值越大越相似 加上负号，表示越相似越靠前
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                .limit(12)  //取前12个
                .collect(Collectors.toList());
        //5.返回结果
        return sortedPictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    @Transactional
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //1.获取和检验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String category = pictureEditByBatchRequest.getCategory();
        if (spaceId == null || loginUser == null || CollUtil.isEmpty(pictureIdList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.校验权限
        Space space = spaceService.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //3.查询指定图片（仅选择需要的图片）
        if (pictureIdList.isEmpty()) {
            return;
        }
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        //4.更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        //批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        //5.操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片编辑失败");
        }
    }

    /**
     * 创建扩图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        //获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));
        //创建扩图任务
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());
        //创建任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);

    }


    /**
     * 点赞/收藏图片
     *
     * @param doPictureRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public boolean doPicture(DoPictureRequest doPictureRequest, User loginUser) {

        if (doPictureRequest == null || loginUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String pictureId = doPictureRequest.getPictureId();
        String action = doPictureRequest.getPictureLoveEnum().name();
        //查记录
        UserPictureAction exist = userPictureActionMapper.selectOne(
                Wrappers.<UserPictureAction>lambdaQuery()
                        .eq(UserPictureAction::getUserId, loginUser.getId())
                        .eq(UserPictureAction::getPictureId, pictureId)
                        .eq(UserPictureAction::getType, action));
        //记录存在
        if (exist != null) {
            userPictureActionMapper.deleteById(exist.getId());
            String col = action.equals("LOVE") ? "loveCount" : "collectCount";
            this.lambdaUpdate()
                    .eq(Picture::getId, pictureId)
                    .setSql(col + " = " + col + " - 1")
                    .update();
        } else {
            UserPictureAction record = new UserPictureAction();
            record.setUserId(loginUser.getId());
            record.setPictureId(Long.valueOf(pictureId));
            record.setType(action);
            userPictureActionMapper.insert(record);
            String col = action.equals("LOVE") ? "loveCount" : "collectCount";
            this.lambdaUpdate()
                    .eq(Picture::getId, pictureId)
                    .setSql(col + " = " + col + " + 1")
                    .update();
        }
        return true;
    }

    /**
     * 获取点赞图片
     *
     * @param pageRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<PictureVO> getLovePicture(PageRequest pageRequest, User loginUser) {
        if (loginUser == null) {
            return new Page<>();
        }
        Page<PictureVO> pictureVOPage = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize(), 10);
        // 查询点赞的图片ID
        List<UserPictureAction> pictureLoveActions = userPictureActionService.list(
                Wrappers.<UserPictureAction>lambdaQuery()
                        .eq(UserPictureAction::getUserId, loginUser.getId())
                        .eq(UserPictureAction::getType, PictureLoveEnum.LOVE.name()));

        // 提取图片ID集合
        return getPictureToBeVOPage(loginUser, pictureLoveActions, pictureVOPage);
    }

    /**
     * 获取收藏图片
     *
     * @param pageRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<PictureVO> getCollectPicture(PageRequest pageRequest, User loginUser) {
        if (loginUser == null) {
            return new Page<>();
        }
        Page<PictureVO> pictureVOPage = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize(), 10);
        // 查询收藏的图片ID
        List<UserPictureAction> pictureCollectActions = userPictureActionService.list(
                Wrappers.<UserPictureAction>lambdaQuery()
                        .eq(UserPictureAction::getUserId, loginUser.getId())
                        .eq(UserPictureAction::getType, PictureLoveEnum.COLLECT.name()));
        return getPictureToBeVOPage(loginUser, pictureCollectActions, pictureVOPage);
    }

    /**
     * 获取待处理的图片
     *
     * @param loginUser
     * @param pictureCollectActions
     * @param pictureVOPage
     * @return
     */
    private Page<PictureVO> getPictureToBeVOPage(User loginUser, List<UserPictureAction> pictureCollectActions, Page<PictureVO> pictureVOPage) {
        // 提取图片ID集合
        List<Long> pictureIdList = pictureCollectActions.stream()
                .map(UserPictureAction::getPictureId)
                .collect(Collectors.toList());

        // 分页处理ID
        int total = pictureIdList.size();
        int current = (int) pictureVOPage.getCurrent();
        int pageSize = (int) pictureVOPage.getSize();
        int fromIndex = Math.min((current - 1) * pageSize, total);
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<Long> pageIdList = pictureIdList.subList(fromIndex, toIndex);

        // 批量查询当前页图片
        List<Picture> pictures = this.listByIds(pageIdList);

        // 转换为PictureVO列表
        List<PictureVO> pictureVOList = pictures.stream()
                .map(p -> {
                    PictureVO vo = PictureVO.objToVo(p);
                    // 判断是否已点赞
                    UserPictureAction exist = userPictureActionMapper.selectOne(
                            Wrappers.<UserPictureAction>lambdaQuery()
                                    .eq(UserPictureAction::getUserId, loginUser.getId())
                                    .eq(UserPictureAction::getPictureId, p.getId())
                                    .eq(UserPictureAction::getType, PictureLoveEnum.LOVE.name()));
                    vo.setHasLoved(exist != null);
                    // 获取是否已收藏
                    exist = userPictureActionMapper.selectOne(
                            Wrappers.<UserPictureAction>lambdaQuery()
                                    .eq(UserPictureAction::getUserId, loginUser.getId())
                                    .eq(UserPictureAction::getPictureId, p.getId())
                                    .eq(UserPictureAction::getType, PictureLoveEnum.COLLECT.name()));
                    vo.setHasCollected(exist != null);
                    return vo;
                }).collect(Collectors.toList());

        pictureVOPage.setRecords(pictureVOList);
        pictureVOPage.setTotal(total);
        return pictureVOPage;

    }

    /**
     * 获取我发布在公共图库的图片（通过审核）
     *
     * @param pageRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<PictureVO> getMyPicture(PageRequest pageRequest, User loginUser) {
        if (loginUser == null) {
            return new Page<>();
        }
        Page<Picture> picturePage = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
        // 直接分页查询
        Page<Picture> pageResult = this.page(
                picturePage,
                Wrappers.<Picture>lambdaQuery()
                        .eq(Picture::getUserId, loginUser.getId())
                        .isNull(Picture::getSpaceId)
                        .eq(Picture::getIsDelete, 0)
                        .eq(Picture::getReviewStatus, 1)
        );
        // 转VO
        List<PictureVO> pictureVOList = pageResult.getRecords().stream()
                .map(p -> {
                    PictureVO vo = PictureVO.objToVo(p);
                    // 判断是否已点赞
                    UserPictureAction exist = userPictureActionMapper.selectOne(
                            Wrappers.<UserPictureAction>lambdaQuery()
                                    .eq(UserPictureAction::getUserId, loginUser.getId())
                                    .eq(UserPictureAction::getPictureId, p.getId())
                                    .eq(UserPictureAction::getType, PictureLoveEnum.LOVE.name()));
                    vo.setHasLoved(exist != null);
                    // 获取是否已收藏
                    exist = userPictureActionMapper.selectOne(
                            Wrappers.<UserPictureAction>lambdaQuery()
                                    .eq(UserPictureAction::getUserId, loginUser.getId())
                                    .eq(UserPictureAction::getPictureId, p.getId())
                                    .eq(UserPictureAction::getType, PictureLoveEnum.COLLECT.name()));
                    vo.setHasCollected(exist != null);
                    return vo;
                }).collect(Collectors.toList());
        // 构造VO分页
        Page<PictureVO> voPage = new Page<>(pageResult.getCurrent(), pageResult.getSize(), pageResult.getTotal());
        voPage.setRecords(pictureVOList);
        return voPage;
    }


    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }


    /**
     * 获取图片主色调
     *
     * @param key 文件 key
     * @return 图片主色调
     */
    public String getImageAve(String key) {
        //创建获取对象的请求
        GetObjectRequest getObj = new GetObjectRequest(cosClientConfig.getBucket(), key);
        //设置图片处理规则为主色调
        String rule = "imageAve";
        getObj.putCustomQueryParameter(rule, null);
        //获取对象
        COSObject object = cosClient.getObject(getObj);
        COSObjectInputStream objectContent = object.getObjectContent();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            CloseableHttpResponse httpResponse = httpClient.execute(objectContent.getHttpRequest());
            String response = EntityUtils.toString(httpResponse.getEntity());
            return JSONUtil.parseObj(response).getStr("RGB");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }
}